package com.benzhuo.widget.pullableview;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import com.benzhuo.widget.common.thread.UiThreadExecutor;


/**
 * 自定义的布局，用来管理三个子控件，其中一个是下拉头，一个是包含内容的pullableView（可以是实现Pullable接口的的任何View），
 * 还有一个上拉头，更多详解见博客http://blog.csdn.net/zhongkejingwang/article/details/38868463
 * 
 * @author 陈靖
 */
public class PullToRefreshLayout extends RelativeLayout
{
	// 刷新回调接口
	private OnRefreshListener mListener;
	// 按下Y坐标，上一个事件点Y坐标
	private float downY;
	private float lastY;

	// 下拉的距离。注意：pullDownY和pullUpY不可能同时不为0
	public float pullDownY = 0;
	// 上拉的距离
	private float pullUpY = 0;

	private MyTimer timer;
	// 回滚速度
	public float MOVE_SPEED = 8;
	// 在刷新过程中滑动操作
	private boolean isTouch = false;
	// 手指滑动距离与下拉头的滑动距离比，中间会随正切函数变化
	private float radio = 2;
	// 下拉头
	private IHeadView headView;
	private boolean canPullHead;
	// 上拉头
	private IFootView footView;
	private boolean canPullFoot;

	// 实现了Pullable接口的View
	private View pullableView;
	// 过滤多点触碰
	private int mEvents;
	// 这两个变量用来控制pull的方向，如果不加控制，当情况满足可上拉又可下拉时没法下拉
	private boolean canPullDown = true;
	private boolean canPullUp = true;
	private ExecutorService executorService = Executors.newSingleThreadExecutor();
	/**
	 * 执行自动回滚的handler
	 */
	Handler updateHandler = new Handler(){

		@Override
		public void handleMessage(Message msg)
		{
			// 回弹速度随下拉距离moveDeltaY增大而增大
			MOVE_SPEED = (float) (8 + 5 * Math.tan(Math.PI / 2
					/ getMeasuredHeight() * (pullDownY + Math.abs(pullUpY))));
			if (!isTouch)
			{
				// 正在刷新，且没有往上推的话则悬停，显示"正在刷新..."
				if (headView!=null&&headView.getState() == IHeadView.STATE_LOADING && pullDownY <= headView.getDist())
				{
					pullDownY =  headView.getDist();
					timer.cancel();
				} else if (footView!=null&&footView.getState() == IFootView.STATE_LOADING && -pullUpY <= footView.getDist())
				{
					pullUpY = -footView.getDist();
					timer.cancel();
				}

			}
			if (pullDownY > 0)
				pullDownY -= MOVE_SPEED;
			else if (pullUpY < 0)
				pullUpY += MOVE_SPEED;
			if (pullDownY < 0)
			{
				// 已完成回弹
				pullDownY = 0;
//				// 隐藏下拉头时有可能还在刷新，只有当前状态不是正在刷新时才改变状态
				if (headView!=null&&headView.getState() != IHeadView.STATE_LOADING){
					headView.setState(IHeadView.STATE_INIT);
				}
				timer.cancel();
				requestLayout();
			}
			if (pullUpY > 0)
			{
				// 已完成回弹
				pullUpY = 0;
//				// 隐藏上拉头时有可能还在刷新，只有当前状态不是正在刷新时才改变状态
				if (footView!=null) {
					if (footView.getState()==IFootView.STATE_REMOVE){
						removeFootView();
					}else if (footView.getState() != IFootView.STATE_LOADING){
						footView.setState(IFootView.STATE_INIT);
					}
				}
				timer.cancel();
				requestLayout();
			}
			Log.d("handle", "handle");
			// 刷新布局,会自动调用onLayout
			requestLayout();
			// 没有拖拉或者回弹完成
			if (pullDownY + Math.abs(pullUpY) == 0)
				timer.cancel();
		}

	};

	private void removeFootView(){
		if (footView!=null){
			this.removeView(footView.getView());
		}
		canPullFoot=false;
	}

	public void setOnRefreshListener(OnRefreshListener listener)
	{
		mListener = listener;
	}

	public PullToRefreshLayout(Context context)
	{
		super(context);
		initView(context);
	}

	public PullToRefreshLayout(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		initView(context);
	}

	public PullToRefreshLayout(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
		initView(context);
	}

	private void initView(Context context)
	{
		timer = new MyTimer(updateHandler);
	}

	private void hide()
	{
		timer.schedule(5);
	}

	/**
	 * 完成刷新操作，显示刷新结果。注意：刷新完成后一定要调用这个方法
	 */
	/**
	 * @param success
	 *            PullToRefreshLayout.SUCCEED代表成功，PullToRefreshLayout.FAIL代表失败
	 */
	private void refreshFinish(boolean success){
		headView.setLoadResult(success);

		if (pullDownY > 0)
		{
			// 刷新结果停留1秒
			new Handler()
			{
				@Override
				public void handleMessage(Message msg)
				{
					headView.setState(IHeadView.STATE_DONE);
					hide();
				}
			}.sendEmptyMessageDelayed(0, 1000);
		} else
		{
			headView.setState(IHeadView.STATE_DONE);
			hide();
		}
	}

	/**
	 * 加载完毕，显示加载结果。注意：加载完成后一定要调用这个方法
	 * 
	 * @param loadMoreResult
	 *            PullToRefreshLayout.SUCCEED代表成功，PullToRefreshLayout.FAIL代表失败
	 */
	private void loadmoreFinish(int loadMoreResult)
	{
		int state = IFootView.STATE_DONE;
		switch (loadMoreResult){
			case OnRefreshListener.LOAD_RESULT_SUCCESS:{
				footView.setLoadResult(IFootView.LOAD_RESULT_SUCCESS);
			}break;
			case OnRefreshListener.LOAD_RESULT_FAILD:{
				footView.setLoadResult(IFootView.LOAD_RESULT_FAILD);
			}break;
			case OnRefreshListener.LOAD_RESULT_NO_MORE:{
				state = IFootView.STATE_REMOVE;
				footView.setLoadResult(IFootView.LOAD_RESULT_NO_MORE);
			}break;
		}
		final int footState = state;
		if (pullUpY < 0)
		{
			// 刷新结果停留1秒
			new Handler()
			{
				@Override
				public void handleMessage(Message msg)
				{
					footView.setState(footState);
					hide();
				}
			}.sendEmptyMessageDelayed(0, 1000);
		} else
		{
			footView.setState(footState);
			hide();
		}
	}

	/**
	 * 不限制上拉或下拉
	 */
	private void releasePull()
	{
		canPullDown = true;
		canPullUp = true;
	}

	/*
	 * （非 Javadoc）由父控件决定是否分发事件，防止事件冲突
	 * 
	 * @see android.view.ViewGroup#dispatchTouchEvent(android.view.MotionEvent)
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev){
		switch (ev.getActionMasked())
		{
		case MotionEvent.ACTION_DOWN:
			downY = ev.getY();
			lastY = downY;
			timer.cancel();
			mEvents = 0;
			releasePull();
			break;
		case MotionEvent.ACTION_POINTER_DOWN:
		case MotionEvent.ACTION_POINTER_UP:
			// 过滤多点触碰
			mEvents = -1;
			break;
		case MotionEvent.ACTION_MOVE:
			if (mEvents == 0){
				Pullable pullable = (Pullable) pullableView;
				if (canPullHead&&(pullDownY > 0|| (pullable.canPullDown()&& canPullDown && (!canPullFoot||footView.getState() != IFootView.STATE_LOADING)))){
					// 可以下拉，正在加载时不能下拉
					// 对实际滑动距离做缩小，造成用力拉的感觉
					pullDownY = pullDownY + (ev.getY() - lastY) / radio;
					if (pullDownY < 0)
					{
						pullDownY = 0;
						canPullDown = false;
						canPullUp = true;
					}
					if (pullDownY > getMeasuredHeight())
						pullDownY = getMeasuredHeight();
					if (headView.getState() == IHeadView.STATE_LOADING)
					{
						// 正在刷新的时候触摸移动
						isTouch = true;
					}
				} else if (canPullFoot&&(pullUpY < 0
						|| (((Pullable) pullableView).canPullUp() && canPullUp &&(!canPullHead || headView.getState() != IHeadView.STATE_LOADING))))
				{
					// 可以上拉，正在刷新时不能上拉
					pullUpY = pullUpY + (ev.getY() - lastY) / radio;
					if (pullUpY > 0)
					{
						pullUpY = 0;
						canPullDown = true;
						canPullUp = false;
					}
					if (pullUpY < -getMeasuredHeight()) {
						pullUpY = -getMeasuredHeight();
					}
					if (footView.getState() == IFootView.STATE_LOADING)
					{
						// 正在加载的时候触摸移动
						isTouch = true;
					}
				} else {
					releasePull();
				}
			} else {
				mEvents = 0;
			}
			lastY = ev.getY();
			// 根据下拉距离改变比例
			radio = (float) (2 + 2 * Math.tan(Math.PI / 2 / getMeasuredHeight()
					* (pullDownY + Math.abs(pullUpY))));
			if (pullDownY > 0 || pullUpY < 0) {
				requestLayout();
			}
			if (canPullHead&&pullDownY > 0)
			{
				headView.onTouchMove(pullDownY);
			} else if (canPullFoot&&pullUpY < 0)
			{
				footView.onTouchMove(-pullUpY);
			}
			// 因为刷新和加载操作不能同时进行，所以pullDownY和pullUpY不会同时不为0，因此这里用(pullDownY +
			// Math.abs(pullUpY))就可以不对当前状态作区分了
			if ((pullDownY + Math.abs(pullUpY)) > 8)
			{
				// 防止下拉过程中误触发长按事件和点击事件
				ev.setAction(MotionEvent.ACTION_CANCEL);
			}
			break;
		case MotionEvent.ACTION_UP:
			if ((canPullHead&&pullDownY > headView.getDist()) || (canPullFoot&&-pullUpY > footView.getDist())) {
				// 正在刷新时往下拉（正在加载时往上拉），释放后下拉头（上拉头）不隐藏
				isTouch = false;
			}
			if (canPullHead){
				headView.onTouchUp(pullDownY);
			}
			if (canPullHead&&headView.getState()==IHeadView.STATE_LOADING)
			{
				// 刷新操作
				refresh();
			} else{
				if (canPullFoot){
					footView.onTouchUp(-pullUpY);
					if (footView.getState() == IFootView.STATE_LOADING){
						loadMore();
					}
				}

			}
			hide();
		default:
			break;
		}
		// 事件分发交给父类
		super.dispatchTouchEvent(ev);
		return true;
	}

	/**
	 * 自动刷新
	 */
	public void refreshOnce() {
		UiThreadExecutor.runTask(new Runnable() {
			@Override
			public void run() {
				pullDownY =  headView.getDist();
				headView.onTouchMove(pullDownY);
				headView.setState(IHeadView.STATE_LOADING);
				// 刷新操作
				if (headView.getState()==IHeadView.STATE_LOADING){
					refresh();
				}
			}
		});
	}

	/**
	 * 自动加载
	 */
	public void loadMoreOnce()
	{
		if (!canPullFoot){
			return;
		}
		pullUpY = -footView.getDist();
		requestLayout();
		footView.onTouchMove(-pullUpY);
		footView.setState(IFootView.STATE_LOADING);
		if (footView.getState() == IFootView.STATE_LOADING){
			loadMore();
		}
	}

	private void refresh(){
		if (mListener != null) {
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					final boolean success = mListener.onRefresh(PullToRefreshLayout.this);
					UiThreadExecutor.runTask(new Runnable() {
						@Override
						public void run() {
							refreshFinish(success);
						}
					});
				}
			});
		}
	}

	private void loadMore(){
		// 加载操作
		if (mListener != null) {
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					final int loadMoreResult = mListener.onLoadMore(PullToRefreshLayout.this);
					UiThreadExecutor.runTask(new Runnable() {
						@Override
						public void run() {
							loadmoreFinish(loadMoreResult);
						}
					});
				}
			});
		}
	}

	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();
		for (int i=0;i<getChildCount();i++){
			View v = getChildAt(i);
			if (v instanceof IHeadView){
				headView = (IHeadView)v;
				canPullHead = true;
			}else if (v instanceof IFootView){
				footView = (IFootView)v;
				canPullFoot = true;
			}else if (v instanceof Pullable){
				pullableView = v;
			}
		}
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b){
		Log.d("Test", "Test");
		// 改变子控件的布局，这里直接用(pullDownY + pullUpY)作为偏移量，这样就可以不对当前状态作区分
		if(canPullHead){
			View refreshV = headView.getView();
			refreshV.layout(0,
					(int) (pullDownY + pullUpY) - refreshV.getMeasuredHeight(),
					refreshV.getMeasuredWidth(), (int) (pullDownY + pullUpY));

		}
		pullableView.layout(0, (int) (pullDownY + pullUpY),
				pullableView.getMeasuredWidth(), (int) (pullDownY + pullUpY)
						+ pullableView.getMeasuredHeight());
		if (canPullFoot){
			View loadV=footView.getView();
			loadV.layout(0,
					(int) (pullDownY + pullUpY) + pullableView.getMeasuredHeight(),
					loadV.getMeasuredWidth(),
					(int) (pullDownY + pullUpY) + pullableView.getMeasuredHeight()
							+ loadV.getMeasuredHeight());
		}
	}

	public boolean isCanPullFoot() {
		return canPullFoot;
	}

	public void setCanPullFoot(boolean canPullFoot) {
		if (canPullFoot&&footView==null){
			throw new NullPointerException("footView is NULL");
		}
		this.canPullFoot = canPullFoot;
		if (!canPullFoot){
			removeFootView();
		}else {
			UiThreadExecutor.runTask(new Runnable() {
				@Override
				public void run() {
					removeView(footView.getView());
					addView(footView.getView());
					footView.setState(IFootView.STATE_INIT);
					requestLayout();
				}
			});

		}
	}

	public boolean isCanPullHead() {
		return canPullHead;
	}

	public void setCanPullHead(boolean canPullHead) {
		if (canPullHead&&headView==null){
			throw new NullPointerException("headView is NULL");
		}
		this.canPullHead = canPullHead;
	}

	class MyTimer {
		private Handler handler;
		private Timer timer;
		private MyTask mTask;

		public MyTimer(Handler handler)
		{
			this.handler = handler;
			timer = new Timer();
		}

		public void schedule(long period)
		{
			if (mTask != null)
			{
				mTask.cancel();
				mTask = null;
			}
			mTask = new MyTask(handler);
			timer.schedule(mTask, 0, period);
		}

		public void cancel()
		{
			if (mTask != null)
			{
				mTask.cancel();
				mTask = null;
			}
		}

		class MyTask extends TimerTask
		{
			private Handler handler;

			public MyTask(Handler handler)
			{
				this.handler = handler;
			}

			@Override
			public void run()
			{
				handler.obtainMessage().sendToTarget();
			}

		}
	}

	/**
	 * 刷新加载回调接口
	 * 
	 * @author chenjing
	 * 
	 */
	public interface OnRefreshListener
	{
		int LOAD_RESULT_SUCCESS = 1;
		int LOAD_RESULT_FAILD = 2;
		int LOAD_RESULT_NO_MORE = 3;
		/**
		 * 刷新操作
		 */
		boolean onRefresh(final PullToRefreshLayout pullToRefreshLayout);

		/**
		 * 加载操作
		 */
		int onLoadMore(final PullToRefreshLayout pullToRefreshLayout);
	}

}
